package com.semanticweb.project.search.searchers;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopScoreDocCollector;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.SimpleFSDirectory;

import com.semanticweb.project.search.config.SearchConstants;

public class ResultRetriever {

    private final TopScoreDocCollector collector;

    public ResultRetriever(final int docCount) {
        this.collector = TopScoreDocCollector.create(docCount, true);
    }

    public List<String> getResults(final Query query, final File indexDir) {
        try {
            final Directory fsDir = new SimpleFSDirectory(indexDir);
            final IndexSearcher is = new IndexSearcher(fsDir, true);
            is.search(query, this.collector);
            final List<String> results = new ArrayList<String>();
            final ScoreDoc[] hits = this.collector.topDocs().scoreDocs;
            for (int i = 0; i < this.collector.getTotalHits(); i++) {
                results.add(is.doc(hits[i].doc).get(SearchConstants.KEY_ID));
            }
            is.close();
            return results;
        } catch (final IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}